package com.bsoft.exchange.service;

import com.bsoft.EmrBLService.DataToHtml;
import com.bsoft.EmrBLService.FileUtil;
import com.bsoft.exchange.dao.emr.RecordMapper;
import com.bsoft.exchange.dao.emr.TemplateMapper;
import com.bsoft.exchange.dao.his.*;
import com.bsoft.exchange.dao.omr.ClinicRecordMapper;
import com.bsoft.exchange.dao.portal.HospitalInformationMapper;
import com.bsoft.exchange.domain.*;
import com.bsoft.exchange.pojo.*;
import com.bsoft.exchange.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import java.util.*;

@Service
public class ClinicMedicationService {
	
	public static final String FormatStr ="yyyy-MM-dd";
	
	@Autowired
	ClinicMedicationMapper clinicMedicationMapper;
	
	@Autowired
	SystemConfigMapper systemConfigMapper;
	
	@Autowired
	UserConfigMapper userConfigMapper;
	
	@Autowired
	IdentityManager identityManager;
	
	@Autowired
	RegisterMapper registerMapper;
	
	@Autowired
	PatientMapper patientMapper;
	
	@Autowired
	TemplateMapper templateMapper;
	
	@Autowired
	RecordMapper recordMapper;
	@Autowired
	ClinicRecordMapper clinicRecordMapper;
	@Autowired
	HospitalInformationMapper hospitalInformationMapper;
	@Autowired
	RecordService recordService;

	@Autowired
	PublicService publicService;
	private List<Integer> ypxhList;
	private List<Integer> ypcdList;

	/**
	 * 获取药房药品信息。
	 * @return
	 */
	public BaseResponse<SyncDrugInformationDomain> syncDrugInformation (SyncDrugInformationPojo syncDrugInformationPojo){
		
		BaseResponse<SyncDrugInformationDomain> response = new BaseResponse<>();
		response.setCode(Constant.successResponse);
		response.setData(null);
		try {
			
			 Long jgid;

	         if(syncDrugInformationPojo.getOrganizationId() == null || "".equals(syncDrugInformationPojo.getOrganizationId())){
	        	 response.setCode(Constant.errorTag);
	        	 response.setMessage("医院识别代码不能为空!");
	        	  
	             return response;
	         }
	           
	        jgid = Long.parseLong(syncDrugInformationPojo.getOrganizationId());
	         Integer yfsb = 0;
			if(syncDrugInformationPojo.getPharmacyCode() == null || "".equals(syncDrugInformationPojo.getPharmacyCode())){
				yfsb = 0;
			}else{
				yfsb = Integer.parseInt(syncDrugInformationPojo.getPharmacyCode());
			}
			//分页
			PageHelper.startPage(syncDrugInformationPojo.getPageNo(),syncDrugInformationPojo.getPageSize());

			List<DrugInfoDomain> medicationList = clinicMedicationMapper.syncDrugInformation(jgid,
					syncDrugInformationPojo.getKeyWord(),yfsb,syncDrugInformationPojo.getDrugType());

			PageInfo <DrugInfoDomain> page = new PageInfo<DrugInfoDomain>(medicationList);

			SyncDrugInformationDomain syncDrug = new SyncDrugInformationDomain();
			syncDrug.setList(medicationList);
			syncDrug.setTotal(page.getTotal());
			if(medicationList == null ||medicationList.size() < 1){
	        	response.setMessage("未查询到数据！");
	        }else{

			    for(DrugInfoDomain drug :medicationList){
			        List<Map<String, Object>> ypqxList = clinicMedicationMapper.getYpqx(Long.parseLong(drug.getDrugId()));
					Map<String, Object> drugAuthority = new HashMap<String, Object>();
			        for(Map<String, Object> ypqx :ypqxList ){
						drugAuthority.put(ypqx.get("QXBM").toString(),ypqx.get("QXMC"));
					}
                    drug.setDrugAuthority(drugAuthority);
                }

	        	response.setMessage("处理成功");
				response.setData(syncDrug);
	        }
			
		} catch (Exception e) {
			e.printStackTrace();
			response.setCode(Constant.errorTag);
			response.setMessage("处理失败"+e.getMessage());
		}
		
		
		return response;
	}
	
	/**
	 * 同步药品煎法信息。
	 * @return
	 */
	public BaseResponse<List<GetDrugDecoctionDomain>> getDrugDecoction(OrganizationIdPojo organizationIdPojo){
		
		BaseResponse<List<GetDrugDecoctionDomain>> response = new BaseResponse<>();
		response.setCode(Constant.successResponse);
		response.setData(null);
		try {
			
			 Long jgid;

	         if(organizationIdPojo.getOrganizationId() == null || "".equals(organizationIdPojo.getOrganizationId())){
	        	 /*response.setCode(Constant.errorTag);
	        	 response.setMessage("医院识别代码不能为空!");
	        	  
	             return response;*/
	        	 //可以为空，默认0
	        	 jgid = 0L;
	         }else{
	        	 jgid = Long.parseLong(organizationIdPojo.getOrganizationId());
	         }
			
			List<GetDrugDecoctionDomain> medicationList = clinicMedicationMapper.getDrugDecoction(jgid);
	
			if(medicationList == null ||medicationList.size() < 1){
	        	response.setMessage("未查询到数据！");
	        }else{
	        	response.setMessage("处理成功");
				response.setData(medicationList);
	        }
			
		} catch (Exception e) {
			e.printStackTrace();
			response.setCode(Constant.errorTag);
			response.setMessage("处理失败"+e.getMessage());
		}
		
		
		return response;
	}

	/**
	 * 获取诊断代码信息。
	 * @return
	 */
	public BaseResponse<SyncDiagnosticInformationDomain> syncDiagnosticInformation (SyncDiagnosticInformationPojo syncDiagnosticInformationPojo){
		
		BaseResponse<SyncDiagnosticInformationDomain> response = new BaseResponse<>();
		response.setCode(Constant.successResponse);
		response.setData(null);
		try {
			
			 Long jgid;

	         if(syncDiagnosticInformationPojo.getOrganizationId() == null || "".equals(syncDiagnosticInformationPojo.getOrganizationId())){
	        	 
	        	 jgid = 0L;
	        	 //response.setMessage("医院识别代码不能为空!"); 
	             //return response;
	         }else{
	        	 jgid = Long.parseLong(syncDiagnosticInformationPojo.getOrganizationId());
	         }

	         //分页
			PageHelper.startPage(syncDiagnosticInformationPojo.getPageNo(),syncDiagnosticInformationPojo.getPageSize());

			List<DiagnosticInfoDomain> diagList = clinicMedicationMapper.syncDiagnosticInformation(jgid,
					syncDiagnosticInformationPojo.getKeyWord(),syncDiagnosticInformationPojo.getDiagnosticType());

			PageInfo<DiagnosticInfoDomain> page = new PageInfo<DiagnosticInfoDomain>(diagList);

			SyncDiagnosticInformationDomain syncDiag = new SyncDiagnosticInformationDomain();
			syncDiag.setList(diagList);
			syncDiag.setTotal(page.getTotal());

			if(diagList == null ||diagList.size() < 1){
	        	response.setMessage("未查询到数据！");
	        }else{
	        	response.setMessage("处理成功");
				response.setData(syncDiag);
	        }
		} catch (Exception e) {
			e.printStackTrace();
			response.setCode(Constant.errorTag);
			response.setMessage("处理失败"+e.getMessage());
		}
		
		
		return response;
	}
	
	/**
	 * 保存门诊诊断信息。
	 * @return
	 */
	@Transactional(value="hisTransactionManager",rollbackFor = Exception.class)
	public BaseResponse<AdmNumberDomain> saveDiagnoseInformation (SaveDiagnoseInformationPojo saveDiagnoseInformationPojo) throws Exception {
		
		BaseResponse<AdmNumberDomain> response = new BaseResponse<>();
		response.setCode(Constant.successResponse);
		response.setData(null);
		/*try {
			*/
			 Long jgid;
			 Long brid ;
			 Long jzxh;
	         if(saveDiagnoseInformationPojo.getOrganizationId() == null || "".equals(saveDiagnoseInformationPojo.getOrganizationId())){
	        	 response.setCode(Constant.errorTag);
	        	 response.setMessage("医院识别代码不能为空!");
	        	  
	             return response;
	         }
	         
	         if(saveDiagnoseInformationPojo.getPatientId() == null || "".equals(saveDiagnoseInformationPojo.getPatientId())){
	        	 response.setCode(Constant.errorTag);
	        	 response.setMessage("患者识别号不能为空!");
	        	  
	             return response;
	         }
	           
	        
	        if(saveDiagnoseInformationPojo.getAdmNumber() == null || "".equals(saveDiagnoseInformationPojo.getAdmNumber())){
	        	response.setCode(Constant.errorTag);
	        	 response.setMessage("就诊序号不能为空!");
	        	  
	             return response;
	         }
	         
	       /* //根据操作类型 operationType; ：0新增、1修改、2删除
	        Integer czlx = saveDiagnoseInformationPojo.getOperationType();
	        if( czlx == null){
	        	response.setCode(Constant.errorTag);
	        	response.setMessage("操作类型不能为空!"); 
	            return response;
	        }*/
	        
	        jgid = Long.parseLong(saveDiagnoseInformationPojo.getOrganizationId());
	        brid = Long.parseLong(saveDiagnoseInformationPojo.getPatientId());
	        jzxh = Long.parseLong(saveDiagnoseInformationPojo.getAdmNumber());
	        
	        YS_MZ_JZLSDomain clinicHistory = clinicMedicationMapper.getClinicHistoryById(jzxh);
	        if(clinicHistory == null){
	        	response.setCode(Constant.errorTag);
	        	response.setMessage("未找到就诊序号为【"+jzxh+"】的就诊记录!"); 
	            return response;
	        }
	        
	        //保存诊断
	        List<SaveDiagnoseDataPojo> diagnoseList = saveDiagnoseInformationPojo.getDiagnosticInformationList();
	        
	        //删除 则 直接删除， 新增和修改 先删除 再新增 0新增、1修改、2删除
	        clinicMedicationMapper.deleteDiagnose(jgid, jzxh);
	        
	        /*if(czlx == 2){
	        	clinicHistory.setZyzd(0L);
	        	clinicHistory.setZdmc("");
	        	clinicHistory.setMqzd("");
	        	clinicMedicationMapper.updateClinicHistory(clinicHistory);
	        	
	        	response.setMessage("处理成功");
	        	return response;
	        }*/

	        /*String czgh = systemConfigMapper.getValueByConfigName(jgid, "ZSYY_MRGH");*/
			DiagnosticInfoDomain diagnosticInformation = new DiagnosticInfoDomain();
	        Long jbxh;
	        String mqzd="";
	        String zdmc ="";
	        Long zyzd = 0L;
	        Integer i=0;
	        Date zdsj;
	        zdsj = new Date();
	        for(SaveDiagnoseDataPojo diag : diagnoseList){
	        	YS_MZ_JBZDDomain diagnose = new YS_MZ_JBZDDomain();
	        	Long jlbh = identityManager.getMax("YS_MZ_JBZD", 1);
	        	Long zdxh = identityManager.getMax("YS_MZ_JBZD_ZDXH", 1);
	        	jbxh = Long.parseLong(diag.getDiagnosticId());
	        	diagnose.setJlbh(jlbh);
	        	diagnose.setJzxh(jzxh);
	        	diagnose.setBrbh(brid);
	        	diagnose.setJbbh(jbxh);
	        	diagnose.setZdlb(11L);//诊断类别
	        	diagnose.setYsdm(clinicHistory.getYsdm());
	        	diagnose.setZdsj(zdsj);
				diagnose.setQzsj(zdsj);
	        	diagnosticInformation = clinicMedicationMapper.getDiagnoseformation(jbxh,diag.getDiagnosticType());
	        	
	        	i++;
	        	mqzd +=i+"."+diagnosticInformation.getDiagnosticName();
	        	if(i == 1){
	        		zyzd = jbxh;
	        		zdmc = diagnosticInformation.getDiagnosticName();
	        	}

                if("1".equals(diag.getMainDiagnosisSign().toString())){
                    zyzd = jbxh;
                    zdmc = diagnosticInformation.getDiagnosticName();
                }

	        	diagnose.setIcd(diagnosticInformation.getDiagnosticCode());
	        	diagnose.setMszd(diagnosticInformation.getDiagnosticName());
	        	diagnose.setJbmc(diagnosticInformation.getDiagnosticName());
	        	diagnose.setZzbj(diag.getMainDiagnosisSign());
	        	diagnose.setJgid(jgid);
	        	diagnose.setZxlb(diag.getDiagnosticType());
	        	diagnose.setZfpb(0);
	        	diagnose.setJbzh("1");
	        	diagnose.setZdlx(1L);
	        	diagnose.setTjbz(1);
	        	diagnose.setZdxh(zdxh);
	        	diagnose.setBkzt(0);
	        	diagnose.setQzbz(0);
	        	diagnose.setDybz(0);
	        	diagnose.setZnxh(1);
	        	clinicMedicationMapper.saveDiagnose(diagnose);
	        }
	        if(diagnoseList.size() == 1){
	        	mqzd = mqzd.substring(2); //只有一个 去掉 1.
	        }

	        /*if(1 ==1){
				throw new Exception("测试异常");
			}*/

	        clinicHistory.setZyzd(zyzd);
	        clinicHistory.setZdmc(zdmc);
	        clinicHistory.setMqzd(mqzd);
	        clinicMedicationMapper.updateClinicHistory(clinicHistory);
	        
			/*AdmNumberDomain admNumber = new AdmNumberDomain();
			admNumber.setAdmNumber(jzxh.toString());
			response.setData(admNumber);*/
			response.setMessage("处理成功");
			
		/*} catch (Exception e) {
			e.printStackTrace();
			response.setCode(Constant.errorTag);
			response.setMessage("处理失败"+e.getMessage());
		}*/
		
		
		return response;
	}
	
	/**
	 * 保存门诊处方信息。
	 * @return
	 */
	@Transactional(value="hisTransactionManager",rollbackFor = Exception.class)
	public BaseResponse<SavePrescriptionInformationDomain> savePrescriptionInformation (SavePrescriptionInformationPojo savePrescriptionInformationPojo) throws Exception {
		
		BaseResponse<SavePrescriptionInformationDomain> response = new BaseResponse<>();
		response.setCode(Constant.successResponse);
		response.setData(null);
		/*try {
			*/
			 Long jgid;
			 Long brid;
			 Long jzxh;
	         if(savePrescriptionInformationPojo.getOrganizationId() == null || "".equals(savePrescriptionInformationPojo.getOrganizationId())){
	        	 response.setCode(Constant.errorTag);
	        	 response.setMessage("医院识别代码不能为空!");
	        	  
	             return response;
	         }
	           
	         if(savePrescriptionInformationPojo.getPatientId() == null || "".equals(savePrescriptionInformationPojo.getPatientId())){
	        	 response.setCode(Constant.errorTag);
	        	 response.setMessage("患者识别号不能为空!");
	        	  
	             return response;
	         }
	           
	        
	        if(savePrescriptionInformationPojo.getAdmNumber() == null || "".equals(savePrescriptionInformationPojo.getAdmNumber())){
	        	response.setCode(Constant.errorTag);
	        	 response.setMessage("就诊序号不能为空!");
	        	  
	             return response;
	         }
	           
	        jgid = Long.parseLong(savePrescriptionInformationPojo.getOrganizationId());
	        brid = Long.parseLong(savePrescriptionInformationPojo.getPatientId());
	        jzxh = Long.parseLong(savePrescriptionInformationPojo.getAdmNumber());
			
	        Long cfsb ;
	        
	        //根据操作类型 operationType; ：0新增、1修改、2删除
	        Integer czlx = savePrescriptionInformationPojo.getOperationType();
	        if( czlx == null){
	        	response.setCode(Constant.errorTag);
	        	response.setMessage("操作类型不能为空!"); 
	            return response;
	        }
	        
	        YS_MZ_JZLSDomain clinicHistory = clinicMedicationMapper.getClinicHistoryById(jzxh);
	        if(clinicHistory == null){
	        	response.setCode(Constant.errorTag);
	        	response.setMessage("未找到就诊序号为【"+jzxh+"】的就诊记录!"); 
	            return response;
	        }
	        
	        SavePrescriptionInformationDomain prescriptionInformation = new SavePrescriptionInformationDomain();
	        prescriptionInformation.setAdmNumber(jzxh.toString());
	        MS_CF01Domain cf01 = null;
	        //修改 删除 需要cfsb
	        if(czlx != 0){
	        	
	        	if(savePrescriptionInformationPojo.getPrescriptionId() == null || "".equals(savePrescriptionInformationPojo.getPrescriptionId())){
		        	response.setCode(Constant.errorTag);
		        	 response.setMessage("当修改或者删除操作时，处方id不能为空!");
		        	  
		             return response;
		         }
	        	cfsb = Long.parseLong(savePrescriptionInformationPojo.getPrescriptionId());
	        	cf01 = clinicMedicationMapper.getMS_CF01ById(cfsb);
	        	
	        	//收费判断
	        	if(cf01 == null){
	        		response.setCode(Constant.errorTag);
		        	response.setMessage("未找到处方识别为【"+cfsb+"】的处方记录!"); 
		            return response;
	        	}
	        	if(cf01.getFphm() != null && !"".equals(cf01.getFphm())){
	        		response.setCode(Constant.errorTag);
		        	response.setMessage("该处方已经收费，不能修改或者删除!"); 
		            return response;
	        	}
	        	
	        	if(cf01.getFybz() == 1){
	        		response.setCode(Constant.errorTag);
		        	response.setMessage("该处方已发药，不能修改或者删除!"); 
		            return response;
	        	}
	        	
	        	//修改 删除 直接先删除该张处方
	        	clinicMedicationMapper.deleteCf02(jgid, cfsb);
		        
	        	clinicMedicationMapper.deleteCf01(jgid, cfsb);
		        
		        if(czlx == 2){
		        	response.setData(prescriptionInformation);
		        	response.setMessage("处理成功");
		        	return response;
		        }

	        }

	        //保存药品
	        List<SaveDrugDataPojo> drugList = savePrescriptionInformationPojo.getPrescriptionDrugList();

	        String czgh = systemConfigMapper.getValueByConfigName(jgid, "ZSYY_MRGH");
	        
	        PatientDomain patient =  patientMapper.getPatientById(brid);
	        
	        // 发药药房  // 费用归并
	        String fyyfCsmc="",fyyf,fygb="2";
	        String fyyfMsg="";
	        Long yfsb ;
	        if(savePrescriptionInformationPojo.getItemType() == 1){
	        	fyyfCsmc = "YS_MZ_FYYF_XY" + "_" +clinicHistory.getKsdm();
	        	
	        	fygb = systemConfigMapper.getValueByConfigName(jgid, "XYF");
		        if(fygb ==null || "".equals(fygb)){
		        	fyyf = "2";
		        }
				fyyfMsg = "科室【"+clinicHistory.getKsdm()+"】默认西药药房";
	        }
	        if(savePrescriptionInformationPojo.getItemType() == 2){
	        	fyyfCsmc = "YS_MZ_FYYF_ZY" + "_" +clinicHistory.getKsdm();
	        	fygb = systemConfigMapper.getValueByConfigName(jgid, "ZYF");
		        if(fygb ==null || "".equals(fygb)){
		        	fyyf = "3";
		        }
				fyyfMsg = "科室【"+clinicHistory.getKsdm()+"】默认中药药房";
	        }
	        if(savePrescriptionInformationPojo.getItemType() == 3){
	        	fyyfCsmc = "YS_MZ_FYYF_CY" + "_" +clinicHistory.getKsdm();
	        	fygb = systemConfigMapper.getValueByConfigName(jgid, "CYF");
		        if(fygb ==null || "".equals(fygb)){
		        	fyyf = "4";
		        }
				fyyfMsg = "科室【"+clinicHistory.getKsdm()+"】默认草药药房";
	        }
	        
	        fyyf = systemConfigMapper.getValueByConfigName(jgid, fyyfCsmc);
	        if(fyyf ==null || "".equals(fyyf)){
	        	fyyf = "-1";
	        }
	        String cyjf;
	        Long ypxh;
	        Long ypcd;
	        Integer cfts ;
	        
	        GY_SYPCDomain sypc = new GY_SYPCDomain();
	        DrugInformationDomain drugInfo = new DrugInformationDomain();

			List<GY_SYPCDomain> sypcList = new ArrayList<GY_SYPCDomain>();
			Integer mrcs =1; //默认1

	        Long cfhm;
	        if(czlx == 0){
	        	cf01 = new MS_CF01Domain();
	        	cfsb = identityManager.getMax("MS_CF01", 1);
	        	cfhm = identityManager.getMax("MS_CF01_CFHM", 1);
	        }else{
	        	cfsb = cf01.getCfsb();
	        	cfhm = Long.parseLong(cf01.getCfhm());
	        }
	
	        cfts = savePrescriptionInformationPojo.getRecipeNumber();
	        if(cfts == null || cfts <= 0){
	        	cfts = 1;
	        }
	        yfsb = Long.parseLong(savePrescriptionInformationPojo.getPharmacyCode());
	        cf01.setCfsb(cfsb);
	        cf01.setCfhm(cfhm.toString());
	        cf01.setJgid(jgid);
	        cf01.setBrid(brid);
	        cf01.setBrxm(patient.getBrxm());
	        cf01.setCflx(savePrescriptionInformationPojo.getItemType());
	        Date kfrq = new Date();
	        cf01.setKfrq(kfrq);
	        cf01.setCfts(cfts);
	        cf01.setKsdm(clinicHistory.getKsdm());
	        cf01.setYsdm(clinicHistory.getYsdm());
	        cf01.setFybz(0);
	        cf01.setZfpb(0);
	        cf01.setDybz(0);
	        cf01.setPybz(0);
	        cf01.setTybz(0);
	        cf01.setTscf(0);
	        cf01.setTslx(0L);
	        cf01.setYfsb(yfsb);
	        cf01.setCfbz(0);
	        cf01.setJzxh(jzxh);
	        cf01.setDjly(99L); //1医生开单 2药房划价 3药房退药 4医技划价 5体检开单 6收费划价 7门诊退费    8.急诊护理    新增 99.互联网移动端医生开单
	        cf01.setBrxz(patient.getBrxz());
	        cf01.setDjybz(savePrescriptionInformationPojo.getBoilSign());
			cf01.setYxpb(0);

	        clinicMedicationMapper.saveCf01(cf01);
	        
	        for(SaveDrugDataPojo drug : drugList){
	        	MS_CF02Domain cf02 = new MS_CF02Domain();
	        	Long sbxh = identityManager.getMax("MS_CF02", 1);
	        	cf02.setSbxh(sbxh);
	        	cf02.setJgid(jgid);
	        	cf02.setCfsb(cfsb);
	        	ypxh = Long.parseLong(drug.getItemCode());
	        	ypcd = Long.parseLong(drug.getFactoryId());
	        	cf02.setYpxh(ypxh);
	        	cf02.setYpcd(ypcd);
	        	
	        	//根据药品序号 和药品产地获取药品信息 	
	        	drugInfo = clinicMedicationMapper.getDrugInformation(jgid,yfsb,ypxh,ypcd);
	        	if(drugInfo == null){
					/*response.setCode(Constant.errorTag);
					response.setMessage(fyyfMsg+"【"+yfsb+"】未找到该药品，请核对默认药房");
					return response;*/
					throw new Exception(fyyfMsg+"【"+yfsb+"】未找到该药品，请核对默认药房");

				}
	        	cf02.setXmlx(savePrescriptionInformationPojo.getItemType());
	        	cfts = savePrescriptionInformationPojo.getRecipeNumber();
	        	if(cfts == null || cfts <= 0){
	        		cfts = 1;
	        	}
	        	cf02.setCfts(cfts);
	        	cf02.setYpsl(drug.getItemNumber());
	        	cf02.setYpdj(drugInfo.getPrice());
	        	cf02.setHjje(drugInfo.getPrice() * drug.getItemNumber() );
	        	cyjf = drug.getDecoctionCode();
	        	if(cyjf == null || "".equals(cyjf)){
	        		cyjf = "1";
	        	}
	        	cf02.setYpzs(Long.parseLong(cyjf));
	        	cf02.setYcsl("0");
	        	cf02.setFygb(Long.parseLong(fygb));
	        	cf02.setZfbl(1.00);
	        	/*cf02.setGytj(Integer.parseInt(drug.getFrequencyCode()));
	        	cf02.setYpyf(drug.getUsageCode());*/

				cf02.setGytj(Integer.parseInt(drug.getUsageCode()));
				cf02.setYpyf(drug.getFrequencyCode());

	        	cf02.setYpzh(drug.getGroupNumber().longValue());
	        	cf02.setYfgg(drugInfo.getSpecifications());
	        	cf02.setYfdw(drugInfo.getUnit());
	        	cf02.setYfbz(drugInfo.getPharmacyPackage());
	        	cf02.setPspb(0);
	        	cf02.setYyts(drug.getDays().longValue());
	        	
	        	//根据药品用法获取每日次数

				sypcList = clinicMedicationMapper.getSypc(0L,drug.getFrequencyCode());
				if(sypcList != null && sypcList.size() > 0){
					sypc = sypcList.get(0);
					mrcs = sypc.getMrcs();
				}else{
					mrcs = 1; //默认1
				}

	        	cf02.setMrcs(mrcs);
	        	cf02.setCfbz(drug.getRemark());
	        	cf02.setYcjl(drug.getDrugDose());
	        	cf02.setPlxh(drug.getSortNumber());
	        	cf02.setSybz(0);
	        	cf02.setBspb(0);
	        	cf02.setSfjg(0);
	        	
	        	clinicMedicationMapper.saveCf02(cf02);
	        }

	        /*if(1 ==1){
				throw new Exception("测试异常");
			}*/

			prescriptionInformation.setCreationTime(kfrq);
	        prescriptionInformation.setPrescriptionId(cfsb.toString());
	        prescriptionInformation.setPrescriptionNumber(cfhm.toString());
			response.setData(prescriptionInformation);
			response.setMessage("处理成功");
		/*} catch (Exception e) {
			e.printStackTrace();
			response.setCode(Constant.errorTag);
			response.setMessage("处理失败"+e.getMessage());
		}*/
		
		
		return response;
	}
	
	
	/**
	 * 获取门诊就诊记录。
	 * @return
	 */
	public BaseResponse<AdmNumberDomain> getVisitingRecord(GetVisitingRecordPojo getVisitingRecordPojo){
		
		BaseResponse<AdmNumberDomain> response = new BaseResponse<>();
		response.setCode(Constant.successResponse);
		response.setData(null);
		try {
			
			 Long jgid;
			 Long brid;
			 Long ghxh;
	         if(getVisitingRecordPojo.getOrganizationId() == null || "".equals(getVisitingRecordPojo.getOrganizationId())){
	        	 response.setCode(Constant.errorTag);
	        	 response.setMessage("医院识别代码不能为空!"); 
	             return response;
	         }
	       
	        
	        if(getVisitingRecordPojo.getPatientId() == null || "".equals(getVisitingRecordPojo.getPatientId())){
	        	response.setCode(Constant.errorTag);
	        	 response.setMessage("患者识别号不能为空!");
	        	  
	             return response;
	         }
	        
	        if(getVisitingRecordPojo.getRegisteredSerialNo() == null || "".equals(getVisitingRecordPojo.getRegisteredSerialNo())){
	        	response.setCode(Constant.errorTag);
	        	 response.setMessage("挂号序号不能为空!");
	             return response;
	         }
	        jgid = Long.parseLong(getVisitingRecordPojo.getOrganizationId());
	        brid = Long.parseLong(getVisitingRecordPojo.getPatientId());
			ghxh = Long.parseLong(getVisitingRecordPojo.getRegisteredSerialNo());
	        
	        BaseResponse<YS_MZ_JZLSDomain> clinicHistoryResponse  = getClinicHistory(jgid,brid,ghxh);
	        
	        //未正确返回就诊记录 返回message
	        if(clinicHistoryResponse.getData() == null){
	        	response.setCode(Constant.errorTag);
	        	response.setMessage("未找到或插入正确就诊记录，"+clinicHistoryResponse.getMessage());
	        	  
	             return response;
	        }
	        
	        Long jzxh ;
	        jzxh = clinicHistoryResponse.getData().getJzxh();
	        
	        AdmNumberDomain admNumber = new AdmNumberDomain();
			admNumber.setAdmNumber(jzxh.toString());
			response.setData(admNumber);
			response.setMessage("处理成功");
		} catch (Exception e) {
			e.printStackTrace();
			response.setCode(Constant.errorTag);
			response.setMessage("处理失败"+e.getMessage());
		}
		
		
		return response;
	}
	
	/**
	 * 查询门诊诊断信息。
	 * @return
	 */
	public BaseResponse<List<GetDiagInfoDomain>> getDiagnoseInformation(AdmNumberPojo admNumberPojo){
		
		BaseResponse<List<GetDiagInfoDomain>> response = new BaseResponse<>();
		response.setCode(Constant.successResponse);
		response.setData(null);
		try {
			
			 Long jgid;
			 Long jzxh;
	         if(admNumberPojo.getOrganizationId() == null || "".equals(admNumberPojo.getOrganizationId())){
	        	 response.setCode(Constant.errorTag);
	        	 response.setMessage("医院识别代码不能为空!"); 
	             return response;
	         }
	        jgid = Long.parseLong(admNumberPojo.getOrganizationId());
	        
	        if(admNumberPojo.getAdmNumber() == null || "".equals(admNumberPojo.getAdmNumber())){
	        	response.setCode(Constant.errorTag);
	        	 response.setMessage("就诊序号不能为空!"); 
	             return response;
	         }
	        jzxh = Long.parseLong(admNumberPojo.getAdmNumber());
	        
			List<GetDiagInfoDomain> diagList = clinicMedicationMapper.getDiagnoseInformation(jgid,jzxh);	
			
			if(diagList == null ||diagList.size() < 1){
	        	response.setMessage("未查询到数据！");
	        }else{
	        	//第一条打上主诊断标志
				diagList.get(0).setMainDiagnosisSign(1);
				response.setMessage("处理成功");
				response.setData(diagList);
	        }

		} catch (Exception e) {
			e.printStackTrace();
			response.setCode(Constant.errorTag);
			response.setMessage("处理失败"+e.getMessage());
		}
		
		
		return response;
	}
	
	/**
	 * 查询门诊处方信息。
	 * @return
	 */
	public BaseResponse<List<GetPrescriptionInformationDomain>> getPrescriptionInformation(AdmNumberPojo admNumberPojo){
		
		BaseResponse<List<GetPrescriptionInformationDomain>> response = new BaseResponse<>();
		response.setCode(Constant.successResponse);
		response.setData(null);
		try {
			
			 Long jgid;
			 Long jzxh;
	         if(admNumberPojo.getOrganizationId() == null || "".equals(admNumberPojo.getOrganizationId())){
	        	 response.setCode(Constant.errorTag);
	        	 response.setMessage("医院识别代码不能为空!"); 
	             return response;
	         }
	        jgid = Long.parseLong(admNumberPojo.getOrganizationId());

			List<HospitalInformation> hospitalInformationList = hospitalInformationMapper.selectList(admNumberPojo.getOrganizationId());
	        if(admNumberPojo.getAdmNumber() == null || "".equals(admNumberPojo.getAdmNumber())){
	        	response.setCode(Constant.errorTag);
	        	 response.setMessage("就诊序号不能为空!"); 
	             return response;
	         }
	        jzxh = Long.parseLong(admNumberPojo.getAdmNumber());
	        
			List<GetPrescriptionInformationDomain> presList = clinicMedicationMapper.getPrescriptionInformation(jgid,jzxh);
			
			if(presList == null ||presList.size() < 1){
	        	response.setMessage("未查询到数据！");
	        }else{

				for(GetPrescriptionInformationDomain pres:presList){
					for (HospitalInformation yymc:hospitalInformationList){
						if (pres.getOrganizationId().equals(yymc)){
							pres.setOrganizationName(yymc.getOrganizationName());
						}
					}
				}

	        	response.setMessage("处理成功");
				response.setData(presList);
	        }

		} catch (Exception e) {
			e.printStackTrace();
			response.setCode(Constant.errorTag);
			response.setMessage("处理失败"+e.getMessage());
		}
		
		
		return response;
	}
	
	/**
	 * 查询门诊病历信息。
	 * @return
	 */
	public BaseResponse<List<GetMedicalRecordInformationDomain>> getMedicalRecordInformation(AdmNumberPojo admNumberPojo,
																							 HttpServletRequest request){
		
		BaseResponse<List<GetMedicalRecordInformationDomain>> response = new BaseResponse<>();
		response.setCode(Constant.successResponse);
		response.setData(null);
		try {
			
			 Long jgid;
			 Long jzxh;
	         if(admNumberPojo.getOrganizationId() == null || "".equals(admNumberPojo.getOrganizationId())){
	        	 response.setCode(Constant.errorTag);
	        	 response.setMessage("医院识别代码不能为空!"); 
	             return response;
	         }
	        jgid = Long.parseLong(admNumberPojo.getOrganizationId());
	        
	        if(admNumberPojo.getAdmNumber() == null || "".equals(admNumberPojo.getAdmNumber())){
	        	response.setCode(Constant.errorTag);
	        	 response.setMessage("就诊序号不能为空!"); 
	             return response;
	         }
	        jzxh = Long.parseLong(admNumberPojo.getAdmNumber());
	        
			String lbbmc ;
			Long bllb,mblb;
			 //获取所有病历 + 第一份病程即可
	        List<GetMedicalRecordInformationDomain> recordList = clinicMedicationMapper.getClinicMedicalRecordList(jgid,jzxh);
	        for(GetMedicalRecordInformationDomain record : recordList){
	        	
	        	bllb = Long.parseLong(record.getMedicalClassId());
	        	mblb = Long.parseLong(record.getTemplateClassId());
	        	lbbmc = recordMapper.getEmrBllbMc(bllb);
	        	record.setMedicalClassName(lbbmc);
	        	if(bllb.toString().equals(mblb.toString())){
	        		record.setTemplateClassName(lbbmc);;
	        	}else{
	        		record.setTemplateClassName(recordMapper.getEmrBllbMc(mblb));
	        	}
	        	//统一用recordService
				Map<String,Object> result = recordService.getUrlByRecordId(Long.parseLong(record.getMedicalRecordId()),1L,1L);
	        	 //Map<String,Object> result = getClinicUrlByRecordId(Long.parseLong(record.getMedicalRecordId()),1L);
				 if(Long.parseLong(result.get("result").toString()) == 1){
					 //record.setWebAddress(result.get("url").toString());
					 record.setWebAddress(request.getScheme() + "://"
							 + request.getServerName() +":"+ request.getServerPort()+ "/temp/doc/"+result.get("filePathName").toString());
				 }else{
					
				 }
	        }
			if(recordList == null ||recordList.size() < 1){
	        	response.setMessage("未查询到数据！");
	        }else{
	        	response.setMessage("处理成功");
				response.setData(recordList);
	        }

		} catch (Exception e) {
			e.printStackTrace();
			response.setCode(Constant.errorTag);
			response.setMessage("处理失败"+e.getMessage());
		}
		
		
		return response;
	}
	
	/**
	 * 同步药品用法信息。
	 * @return
	 */
	public BaseResponse<List<DrugUsageDomain>> getDrugUsage(OrganizationIdPojo organizationIdPojo){
		
		BaseResponse<List<DrugUsageDomain>> response = new BaseResponse<>();
		response.setCode(Constant.successResponse);
		response.setData(null);
		try {
			
			 Long jgid;
			 if(organizationIdPojo.getOrganizationId() == null || "".equals(organizationIdPojo.getOrganizationId())){
	        	 jgid = 0L;
	        	 /*response.setMessage("医院识别代码不能为空!"); 
	             return response;*/
	         }else{
	        	 jgid = Long.parseLong(organizationIdPojo.getOrganizationId()); 
	         }
	        
			List<DrugUsageDomain> presList = clinicMedicationMapper.getDrugUsage(jgid);	

			if(presList == null ||presList.size() < 1){
	        	response.setMessage("未查询到数据！");
	        }else{
	        	response.setMessage("处理成功");
				response.setData(presList);
	        }
			
		} catch (Exception e) {
			e.printStackTrace();
			response.setCode(Constant.errorTag);
			response.setMessage("处理失败"+e.getMessage());
		}
		
		
		return response;
	}
	
	/**
	 * 同步药品频次信息。
	 * @return
	 */
	public BaseResponse<List<DrugFrequencyDomain>> getDrugFrequency(OrganizationIdPojo organizationIdPojo){
		
		BaseResponse<List<DrugFrequencyDomain>> response = new BaseResponse<>();
		response.setCode(Constant.successResponse);
		response.setData(null);
		try {
			
			 Long jgid;
	         if(organizationIdPojo.getOrganizationId() == null || "".equals(organizationIdPojo.getOrganizationId())){
	        	 jgid = 0L;
	        	 /*response.setMessage("医院识别代码不能为空!"); 
	             return response;*/
	         }else{
	        	 jgid = Long.parseLong(organizationIdPojo.getOrganizationId()); 
	         }

			List<GY_SYPCDomain> sypcList = clinicMedicationMapper.getSypc(jgid,"");	
			List<DrugFrequencyDomain> drugFrequencyList = new ArrayList<DrugFrequencyDomain>();
			String rzxzq = "" ;
			Integer zqcs = 0; //周期次数
			String zxzq=""; //执行周期
			String zxsj;   //执行时间
			String[] arrs;
			String executionTime=""; //执行时间 
			int index;
			
			List<GY_ZXZQDomain> zxzqList = new ArrayList<GY_ZXZQDomain>();
			
			if(sypcList != null &&sypcList.size()>0) {
				for(GY_SYPCDomain sypc : sypcList){
					DrugFrequencyDomain drugFrequency = new DrugFrequencyDomain();
					
					//重置变量
					executionTime="";
					zxzq ="";
					zqcs = 0;
					
					drugFrequency.setFrequencyCode(sypc.getPcbm());
					drugFrequency.setFrequencyName(sypc.getPcmc());
					drugFrequency.setFrequencyCycle(sypc.getZxzq());
					
					if(sypc.getRlz() != 1){
						rzxzq = sypc.getRzxzq();

					}else{
						//日历周 取第一条执行周期
						zxzqList = clinicMedicationMapper.getZxzq(jgid, sypc.getPcbm());
						if(zxzqList != null && zxzqList.size() > 0){
							rzxzq = zxzqList.get(0).getRzxzq();
						}
					}
					
					char[] ch=rzxzq.toCharArray(); 
					 char c='1'; 
					 for(int i = 0; i < ch.length; i++) { 
						 if(c==ch[i]) { 
							 zqcs++;
							if(i == 0 ){
								zxzq += ""+(i+1);
							}else{
								zxzq += ","+(i+1);
							}
						 }
					 }
					
					//执行时间
					zxsj = sypc.getZxsj();
					arrs = zxsj.split("-");
					
					for(String s: arrs){
						index=s.indexOf(":");
						if(index == -1){
							executionTime += ","+s+":00";
						}else{
							executionTime += ","+s;
						}
					}
					//去掉第一个 ","
					executionTime = executionTime.substring(1);
					
			        drugFrequency.setExecutionTime(executionTime);
					drugFrequency.setFrequencyCycleNumber(zqcs);
					drugFrequency.setExecutionCycle(zxzq);
					
					drugFrequencyList.add(drugFrequency);
				}
				response.setMessage("处理成功");
				response.setData(drugFrequencyList);
			}else {
				response.setMessage("未查询到数据！");
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.setCode(Constant.errorTag);
			response.setMessage("处理失败"+e.getMessage());
		}
		
		
		return response;
	}
	
	
	/**根据机构id 病人id 预约序号 获取 门诊就诊记录
	 * @param jgid
	 * @param brid
	 * @return
	 */
	@Transactional(value="hisTransactionManager",rollbackFor = Exception.class)
	public BaseResponse<YS_MZ_JZLSDomain> getClinicHistory(Long jgid,Long brid,Long ghxh){
		BaseResponse<YS_MZ_JZLSDomain> response = new BaseResponse<>();
		response.setData(null);
		//获取预约信息
        Map<String, Object> appoint = clinicMedicationMapper.getAppointmentInfo(jgid, ghxh);
        if(appoint == null){
        	response.setCode(Constant.errorTag);
        	response.setMessage("根据该机构识别号、患者识别号和挂号序号未查询到预约信息!");
            return response;
        }
        
        /*if("0".equals(appoint.get("yyzt").toString())){
        	response.setMessage("该预约信息还未挂号!");
            return response;
        }*/
//        if("2".equals(appoint.get("yyzt").toString())){
//        	response.setCode(Constant.errorTag);
//        	response.setMessage("该预约信息已取消!");
//            return response;
//        }
//        if("3".equals(appoint.get("yyzt").toString())){
//        	response.setCode(Constant.errorTag);
//        	response.setMessage("该预约信息已爽约!");
//            return response;
//        }
//
//        if(appoint.get("ghxh") == null || "0".equals(appoint.get("ghxh").toString())){
//        	response.setCode(Constant.errorTag);
//        	response.setMessage("该预约信息还未挂号!");
//            return response;
//        }
        
        //获取有效效期内的就诊记录
        String ghxq = systemConfigMapper.getValueByConfigName(jgid, "GHXQ"); //挂号效期 默认2天
        if(ghxq == null){
        	ghxq = "2";
        }
        
        Integer regValidDays ;
        regValidDays = (int) Math.round(Double.parseDouble(ghxq) * 24) ;
        
        Date now = new Date();
        Date currentDate = DateUtil.addDateToHour(now,(-1) * regValidDays);
        
        Long ksdm;
        String ysdm;
        Integer czpb;
        
        ksdm = Long.parseLong(appoint.get("mzks").toString());
        ysdm = appoint.get("ysdm").toString();
//        ghxh = Long.parseLong(appoint.get("ghxh").toString());
        YS_MZ_JZLSDomain clinicHistory = clinicMedicationMapper.getClinicHistory(jgid, brid,ksdm , ysdm	, ghxh , currentDate);
        
        //无有效就诊记录 需要插入就诊记录
        if(clinicHistory == null){
        	clinicHistory = new YS_MZ_JZLSDomain();
        	
        	Long jzxh = identityManager.getMax("YS_MZ_JZLS", 1);
        	clinicHistory.setJzxh(jzxh);
        	clinicHistory.setGhxh(ghxh);
        	clinicHistory.setKsdm(ksdm);
        	clinicHistory.setYsdm(ysdm);
        	clinicHistory.setBrbh(brid);
        	clinicHistory.setJgid(jgid);
        	clinicHistory.setKssj(new Date());
        	clinicHistory.setJzzt(1);
        	clinicHistory.setJzlx(3); //就诊类型:1住院病人 2新生儿 3门诊病人 4急诊病人 5留观病人 Dict901
        	
        	//初诊判别
    		czpb = registerMapper.checkFirstVisit(jgid,brid);
    		if(czpb == null || czpb <= 0){
    			czpb = 0;
    		}else{
    			czpb = 1;
    		}
        	
        	clinicHistory.setCzpb(czpb);
        	
        	//保存新的门诊就诊记录
        	clinicMedicationMapper.saveClinicHistory(clinicHistory);
        }
        response.setData(clinicHistory);
		return response;
	}
	
	/**
	 * 更新门诊就诊记录状态。
	 * @return
	 */
	@Transactional(value="hisTransactionManager",rollbackFor = Exception.class)
	public BaseResponse<Object> updateVisitStatus(UpdateVisitStatusPojo updateVisitStatusPojo) throws Exception {
		
		BaseResponse<Object> response = new BaseResponse<>();
		response.setCode(Constant.successResponse);
		response.setData(null);
		/*try {
			*/
			 Long jgid;
			 Long jzxh;
			 Integer jzzt;
			 if(updateVisitStatusPojo.getOrganizationId() == null || "".equals(updateVisitStatusPojo.getOrganizationId())){
				 response.setCode(Constant.errorTag);
	        	 response.setMessage("医院识别代码不能为空!"); 
	             return response;
	         }
	        jgid = Long.parseLong(updateVisitStatusPojo.getOrganizationId()); 
	        
	        if(updateVisitStatusPojo.getAdmNumber() == null || "".equals(updateVisitStatusPojo.getAdmNumber())){
	        	response.setCode(Constant.errorTag);
	        	 response.setMessage("就诊序号不能为空!"); 
	             return response;
	         }
	        jzxh = Long.parseLong(updateVisitStatusPojo.getAdmNumber()); 
	        
	        if(updateVisitStatusPojo.getVisitStatus() == null || "".equals(updateVisitStatusPojo.getVisitStatus())){
	        	response.setCode(Constant.errorTag);
	        	 response.setMessage("就诊状态不能为空!"); 
	             return response;
	         }
	        jzzt = updateVisitStatusPojo.getVisitStatus(); 
	        
	        YS_MZ_JZLSDomain jzls = clinicMedicationMapper.getClinicHistoryById(jzxh);
	        
	        if(jzls == null){
	        	response.setCode(Constant.errorTag);
	        	response.setMessage("未找到就诊序号为【"+jzxh+"】的就诊记录!"); 
	            return response;
	        }
	        
	        Date jssj = new Date();
	        if(jzzt == 1){
	        	jssj = null;
	        }
	        jzls.setJzzt(jzzt);
	        jzls.setJssj(jssj);
			clinicMedicationMapper.updateClinicHistory(jzls);
			
			//结束就诊需要更新ghmx表
			if(jzzt == 9){
				clinicMedicationMapper.updateRegistration(jzls.getGhxh(), jzzt.longValue());
				
			}

			/*if(1 ==1){
				throw new Exception("测试异常");
			}*/

			response.setMessage("处理成功");

		/*} catch (Exception e) {
			e.printStackTrace();
			response.setCode(Constant.errorTag);
			response.setMessage("处理失败"+e.getMessage());
		}*/
		
		
		return response;
	}
	
	/**
	 * 保存门诊病历信息。
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public BaseResponse<Object> saveMedicalRecordInformation(SaveMedicalRecordInformationPojo saveMedicalRecordInformationPojo){
		
		BaseResponse<Object> response = new BaseResponse<>();
		response.setCode(Constant.successResponse);
		response.setData(null);
		try {
			
			 Long jgid;
			 Long jzxh;
			 Long brid;
			 if(saveMedicalRecordInformationPojo.getOrganizationId() == null || "".equals(saveMedicalRecordInformationPojo.getOrganizationId())){
				 response.setCode(Constant.errorTag);
	        	 response.setMessage("医院识别代码不能为空!"); 
	             return response;
	         }
	        jgid = Long.parseLong(saveMedicalRecordInformationPojo.getOrganizationId()); 
	        
	        if(saveMedicalRecordInformationPojo.getAdmNumber() == null || "".equals(saveMedicalRecordInformationPojo.getAdmNumber())){
	        	response.setCode(Constant.errorTag);
	        	 response.setMessage("就诊序号不能为空!"); 
	             return response;
	         }
	        jzxh = Long.parseLong(saveMedicalRecordInformationPojo.getAdmNumber()); 
	        
	        if(saveMedicalRecordInformationPojo.getPatientId() == null || "".equals(saveMedicalRecordInformationPojo.getPatientId())){
	        	response.setCode(Constant.errorTag);
	        	 response.setMessage("病人id不能为空!"); 
	             return response;
	         }
	        brid = Long.parseLong(saveMedicalRecordInformationPojo.getPatientId()); 
	        
	       //根据操作类型 operationType; ：0新增、1修改、2删除
	        Integer czlx = saveMedicalRecordInformationPojo.getOperationType();
	        if( czlx == null){
	        	response.setCode(Constant.errorTag);
	        	response.setMessage("操作类型不能为空!"); 
	            return response;
	        }
	        YS_MZ_JZLSDomain jzls = clinicMedicationMapper.getClinicHistoryById(jzxh);
	        if(jzls == null){
	        	response.setCode(Constant.errorTag);
	        	response.setMessage("未找到【"+jzxh+"】对应的就诊记录!"); 
	            return response;
	        }
	        List<ClinicRecordDomain> clinicRecordList = clinicMedicationMapper.getClinicRecordList(jgid,jzxh,brid); 
	        ClinicRecordDomain omr_bl01 = new ClinicRecordDomain();
	        
	        //理论上只有一份，只操作一份病历
	        if( czlx == 2){
	        	
	        	if(clinicRecordList != null && clinicRecordList.size() > 0){
		        	omr_bl01 = clinicRecordList.get(0); //第一份
		        	omr_bl01.setBlzt(9); //9删除
		        	clinicMedicationMapper.updateClinicRecord(omr_bl01);
		        }	
	        	
	        }else{
	        	if(clinicRecordList != null && clinicRecordList.size() > 0){
		        	omr_bl01 = clinicRecordList.get(0); //第一份	
		        }else{  //新建一份
		        	
		        	//获取默认模板，如果没有设置，怎返回错误
		        	String mbbhS;
		        	Long mbbh ;//模板编号
		        	if(jzls.getCzpb() == 0){
		        		mbbhS = userConfigMapper.getConfigValue(jgid, 2L, jzls.getKsdm().toString(), "dept_use_template");
		        	}else{
		        		mbbhS = userConfigMapper.getConfigValue(jgid, 2L, jzls.getKsdm().toString(), "dept_use_template_fz");
		        	}
		        	if(mbbhS == null || "".equals(mbbhS) ){
		        		response.setCode(Constant.errorTag);
			        	response.setMessage("该就诊科室未设置默认模板无法进行病历保存!"); 
			            return response;
		        	}
		        	
		        	mbbh = Long.parseLong(mbbhS);
		        	if(mbbh <= 0){
		        		response.setCode(Constant.errorTag);
			        	response.setMessage("该就诊科室设置默认模板错误!"); 
			            return response;
		        	}
		        	
		        	//根据模板编号找到病历模板 
		        	Map<String, Object> inArgs = new HashMap<String, Object>();
		        	byte[] blnr=null;
		        	inArgs.put("chtcode", mbbh);
		        	List<ChtemplateDomain> chtList = templateMapper.getBlobFromTemplate(inArgs);
		        	
		        	if(chtList == null || chtList.size() <= 0){
		        		response.setCode(Constant.errorTag);
			        	response.setMessage("该就诊科室设置默认模板未找到!"); 
			            return response;
		        	}
		        	ChtemplateDomain chtemplate = chtList.get(0);
		        	blnr= chtemplate.getXmltextpat(); 
		        	
		        	Date jlsj = new Date();
		        	
		        	Long blbh = identityManager.getMax("OMR_BL01", 1);
		        	omr_bl01.setBlbh(blbh);
		        	omr_bl01.setBrid(brid);
		        	omr_bl01.setJgid(jgid);
		        	omr_bl01.setJzxh(jzxh);
		        	omr_bl01.setBllx(0);
		        	omr_bl01.setBlzt(0);
		        	omr_bl01.setSybz(0);
		        	omr_bl01.setJlsj(jlsj);
		        	omr_bl01.setCjsj(jlsj);
		        	omr_bl01.setSxys(jzls.getYsdm());
		        	omr_bl01.setSxks(jzls.getKsdm());
		        	omr_bl01.setBrks(jzls.getKsdm());
		        	omr_bl01.setPtid(0L);
		        	omr_bl01.setBllb(Long.parseLong(chtemplate.getFrameworkcode()));
		        	omr_bl01.setMblb(Long.parseLong(chtemplate.getTemplatetype()));
		        	omr_bl01.setDllb(0L);
		        	omr_bl01.setDlj("");
		        	omr_bl01.setMbbh(chtemplate.getChtcode());
		        	omr_bl01.setBlmc(chtemplate.getChtname()); //病历名称直接取模板名称
		        	
		        	clinicMedicationMapper.saveClinicRecord(omr_bl01);
		        	
		        }	
	        	
	        }
	        
	        //开始根据模板内容替换 几个段落内容
	        String zs; //主诉
	        String xbs;//现病史
	        String jws;//既往史
	        String fzjc;//辅助检查
	        String tgjc;//体格检查
	        String clyj;//处理意见
	        zs = saveMedicalRecordInformationPojo.getMedicalRecordInformation().getMainComplaint();
	        xbs = saveMedicalRecordInformationPojo.getMedicalRecordInformation().getMedicalHistory();
	        jws = saveMedicalRecordInformationPojo.getMedicalRecordInformation().getPastHistory();
	        fzjc = saveMedicalRecordInformationPojo.getMedicalRecordInformation().getSupplementaryExamination();
	        tgjc = saveMedicalRecordInformationPojo.getMedicalRecordInformation().getPhysicalExamination();
	        clyj = saveMedicalRecordInformationPojo.getMedicalRecordInformation().getHandlingOpinions();
			
	        //开始保存 OMR_BL02、OMR_BLXG、EMR_BLSJRZ表
	        
	        //处理了之后的病历内容
	        String blnr_txt;
	        byte[] blnr;
	        
	        response.setMessage("处理成功");

		} catch (Exception e) {
			e.printStackTrace();
			response.setCode(Constant.errorTag);
			response.setMessage("处理失败"+e.getMessage());
		}
		
		
		return response;
	}
	
	/**
	 * 根据病历编号获取htm的URL recordType ,
	 * 参照病历解析里的html展示
	 * @param type
	 * @param recordId
	 * @return
	 * @throws UnsupportedEncodingException 
	 * @throws MalformedURLException 
	 */
	public Map<String, Object> getClinicUrlByRecordId(Long recordId,Long type ) throws UnsupportedEncodingException, MalformedURLException {
		Map<String, Object> result = new HashMap<String, Object>();

		// 设置存储位置
		String localPath = this.getClass().getClassLoader().getResource("").getPath();
		try {
			localPath = URLDecoder.decode(localPath, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
			result.put("result", 0);
			result.put("errorText", "转UTF-8编码失败!");
			return result;
		}
		if (localPath.indexOf("target") >= 0) {
			localPath = localPath.replace("target/classes/", "src/main/webapp/clinicdoc/");
			localPath = localPath.replace("target/test-classes/", "src/main/webapp/clinicdoc/");
		} else {
			localPath = localPath.replace("WEB-INF/classes/", "clinicdoc/");
		}
		localPath = localPath.substring(1);

		// 查询门诊病历数据  跨库，分两次查询
		RecordDomain record = clinicMedicationMapper.getClinicRecordById(recordId);
		RecordDomain record2 = clinicRecordMapper.getClinicRecordDataById(recordId);
		if (record == null || record2 == null) {
			result.put("result", 0);
			result.put("errorText", "未查询到病历内容!");
			return result;
		}

		record.setBlnr(record2.getBlnr());
		
		// 3种类型不同处理
		// 1.病历:获取内容 通过转换服务转
		// 2.病历:获取所有病程内容 通过转换服务转
		// 3.病案首页:获取内容写html文件

		String filePath = localPath + record.getRecordTypeCode() + "/" ;
		String fileName = "" + record.getRecordId() + ".html";
		String data = new String(record.getBlnr(),"gbk");
		String realPath = filePath + fileName;
		//URL url = new File(realPath).toURI().toURL();
		if(type == 0){
			record.setType(0);
		}
		
		if (record.getRecordType() == 1) {
			// ===================================================================
			// 病案首页
			// ===================================================================
			FileUtil.checkPathExist(filePath);
			if (FileUtil.checkFileExist(realPath) == 0) {
				FileUtil.deleteFile(realPath);
			}
			FileUtil.writeFileByCharsCode(realPath, data, 0);
			if (FileUtil.checkFileExist(realPath) == 0) {
				result.put("result", 1);
				//result.put("url", "/doc/" +record.getRecordTypeCode()+"/"+ fileName);
				result.put("url", new File(realPath).toURI().toURL().toString());
			} else {
				result.put("result", 0);
				result.put("errorText", "生成Html文件失败!");
			}
		} else {

			if (record.getType() == 0) {
				// ===================================================================
				// 病历
				// ===================================================================
				//先获取签名图片
				Map<String, Object> param =getClinicSignMessage(recordId);
				param.put("BLNR", record.getBlnr());
				param.put("realPath", filePath);
				param.put("fileName", fileName);
				param.put("creatHtml", "1");
				boolean i = new DataToHtml().BlobToHtmlView(param);
				if (i == true) {
					result.put("result", 1);
					//result.put("url", "/doc/" +record.getRecordTypeCode()+"/" + fileName);
					result.put("url", new File(realPath).toURI().toURL().toString());
				} else {
					result.put("result", 0);
					result.put("errorText", "生成Html文件失败!");
				}
			} else {
				// ===================================================================
				// 病程
				// ===================================================================
				// 获取页眉页脚
				RecordDomain head = clinicMedicationMapper.getClinicHead(Long.parseLong(record.getVisitId()));
				RecordDomain head2 = clinicRecordMapper.getClinicRecordDataById(head.getRecordId());
				if (head == null || head2 == null) {
					result.put("result", 0);
					result.put("errorText", "未查询到病程的页眉页脚!");
					return result;
				}

				head.setBlnr(head2.getBlnr());
	
				filePath = localPath + record.getRecordTypeCode() + "/" + record.getVisitId() + "/";
				fileName = "" + head.getRecordId() + ".html";
				data = new String(head.getBlnr());
				realPath = filePath + fileName;
				String sHeader = "";
				String sFooter = "";
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("BLNR", head.getBlnr());
				param.put("realPath", filePath);
				param.put("fileName", fileName);
				param.put("creatHtml", "0");
				boolean i = new DataToHtml().BlobToHtmlView(param);
				if (i != true) {
					result.put("result", 0);
					result.put("errorText", "页眉转换HTML失败!");
					return result;
				} else {
					sHeader = (String) param.get("sHeader");
					sFooter = (String) param.get("sFooter");
				}

				// 获取病程记录
				List<RecordDomain> courseList = clinicMedicationMapper.getClinicCourseList(Long.parseLong(record.getVisitId()));
				if (courseList.size() == 0) {
					result.put("result", 0);
					result.put("errorText", "未查询到病程记录!");
					return result;
				}
				
				RecordDomain temp = new RecordDomain();
				
				String strOut="";
				for (RecordDomain detail : courseList) {
					Map<String, Object> courseParam =getClinicSignMessage(detail.getRecordId());
					
					temp = clinicRecordMapper.getClinicRecordDataById(detail.getRecordId());
					detail.setBlnr(temp.getBlnr());
					
					courseParam.put("BLNR", detail.getBlnr());
					courseParam.put("realPath", filePath);
					courseParam.put("fileName", fileName);
					courseParam.put("creatHtml", "0");
					courseParam.put("isParkey", "1"); //病程标记，主要处理据左右问题
			        boolean ire = new DataToHtml().BlobToHtmlView(courseParam);
			        if (ire!=true){
			        	strOut = strOut + "病程编号"+detail.getRecordId()+"转HTML字符串失败";
			        }
			        else {
						String ss=(String)courseParam.get("html");
						sHeader = sHeader + ss;
			        }
				}
                if("".equals(strOut)){
    				// 生成HTML文件
					String sHTML = sHeader + sFooter;
					// 判断路径是否存在
					FileUtil.checkPathExist(filePath);
					FileUtil.writeFileByCharsCode(filePath + fileName, sHTML, 0);
					if (FileUtil.checkFileExist(filePath + fileName) == 0) {
						result.put("result", 1);
						//result.put("url", "/doc/"+record.getRecordTypeCode()+"/" +record.getVisitId()+"/" + fileName);
						result.put("url", new File(realPath).toURI().toURL().toString());
						return result;
					} else {
						result.put("result", 0);
						result.put("errorText", "生成HTML文件失败!");
						return result;
					}
                }else{
					result.put("result", 0);
					result.put("errorText", strOut);
					return result;
                }
			}
		}
		return result;
	}
	
	private Map<String, Object> getClinicSignMessage(Long recordId) {
		Map<String, Object> param = new HashMap<String, Object>();
		
		List<RecordSignDomain> signList = clinicMedicationMapper.getClinicSignList(recordId);
		String signStrList = "";
		for (RecordSignDomain detail : signList) {
			String signRecordId = detail.getSignRecordId().toString();
			String signId = detail.getSignId().toString();
			
			//跨库 重新获取
			//byte[] signImage = detail.getSignFile();
			RecordSignDomain sign = recordMapper.getEmrSignFile(detail.getSignId());
			byte[] signImage = sign.getSignFile();
			String key = signId + "#" + signRecordId;
			String skey = "," + key + ",";
			String sList = "," + signStrList + ",";
			if (!sList.contains(skey) && signImage != null) {
				param.put(key, signImage);
				if ("".equals(signStrList)) {
					signStrList = key;
				} else {
					signStrList = signStrList + "," + key;
				}
			}
		}
		if (!"".equals(signStrList)) {
			param.put("qmlist", signStrList);
		}
		return param;
	}
	/**
	 * 获取处方审核信息
	 */
	public BaseResponse<List<PrescriptionAuditInformation>> getAuditInfo(PrescriptionAuditInformationPojo pojo){
		BaseResponse<List<PrescriptionAuditInformation>> baseResponse=new BaseResponse();

		List<PrescriptionAuditInformation> bridInfo;
		if (!TextUtils.isEmpty(pojo.getCardNumber())&&!TextUtils.isEmpty(pojo.getCardType())){
			bridInfo=clinicMedicationMapper.mzhmGetbridInfo(pojo.getOrganizationId(),null,pojo.getCardNumber(),
					pojo.getBeginTime(),pojo.getEndTime());
		}else if (!TextUtils.isEmpty(pojo.getOutpatientNumber())){
			bridInfo=clinicMedicationMapper.mzhmGetbridInfo(pojo.getOrganizationId(),pojo.getOutpatientNumber(),null,
					pojo.getBeginTime(),pojo.getEndTime());
		}else{
			baseResponse.setCode(Constant.successResponse);
			baseResponse.setMessage("证件和门诊号码不能同时为空");
			return baseResponse;
		}
		if (bridInfo.size()>0) {
			List<DrugInfo> ypmcxxList=publicService.getDrugInfo();
			List<DrugField> cdxxList=publicService.getDrugField();
			List<PrescriptionAuditInformationList> cfxxList=clinicMedicationMapper.getCfAduitInfo(pojo.getOrganizationId(),bridInfo.get(0).getBRID(),
					pojo.getAuditStatus());
			List<DoctorInfo> sfyg = publicService.getDoctorInfo(pojo.getOrganizationId());
			for (PrescriptionAuditInformationList cfxx:cfxxList){
				cfxx.setAuditStatus(cfxx.getPrescriptionDrugList().get(0).getSFJG());
				cfxx.setAuditMind(cfxx.getPrescriptionDrugList().get(0).getSFYJ());
				if (!TextUtils.isEmpty(cfxx.getPrescriptionDrugList().get(0).getSFGH())) {
					for (DoctorInfo doctorInfo:sfyg){
						if (doctorInfo.getYGDM().equals(cfxx.getPrescriptionDrugList().get(0).getSFGH())){
							cfxx.setAuditor(doctorInfo.getYGXM());
							break;
						}
					}
				}
				for (PrescriptionAuditInformationListDrug cf02xx:cfxx.getPrescriptionDrugList()){
					for (DrugInfo ypmcxx:ypmcxxList){
						if (ypmcxx.getYPXH().equals(cf02xx.getYPXH())){
							cf02xx.setDoseUnit(ypmcxx.getZXDW());
							cf02xx.setDrugName(ypmcxx.getYPMC());
							break;
						}
					}
					for (DrugField cdxx:cdxxList){
						if (cdxx.getYPCD().equals(cf02xx.getYPCD())){
							cf02xx.setFactoryName(cdxx.getCDMC());
							break;
						}
					}
				}
			}
			//根据药品序号和药品产地去查对应的名称
			//获取药品序号和药品产地
			for (PrescriptionAuditInformation prescriptionData:bridInfo){
				List<PrescriptionAuditInformationList> zList= new ArrayList<>();
				for (PrescriptionAuditInformationList cfxx:cfxxList){
					if (cfxx.getJZXH().equals(prescriptionData.getJzxh())){
						zList.add(cfxx);
					}
				}
				prescriptionData.setPrescriptionAuditInformationList(zList);
			}
		}
		baseResponse.setCode(Constant.successResponse);
		baseResponse.setMessage("请求成功");
		baseResponse.setData(bridInfo);
		return baseResponse;
	}

}
